<template>
  <div ref="imgScroll" :class="is_comment?'comment_upload_image':'upload_image'">
    <!-- 创建工单时调用的组件 -->
    <van-uploader
      v-model="fileList"
      multiple
      :max-count="maxCount"
      :after-read="uploadImg"
      :before-delete="deleteImg"
      v-if="!is_comment"
      class="van-upload_box"
    />

    <!-- 评论工单时调用的组件 -->
    <van-uploader
      v-model="fileList"
      multiple
      :max-count="maxCount"
      :after-read="uploadImg"
      :before-delete="deleteImg"
      v-if="is_comment"
    >
      <van-button icon="photo" type="primary"></van-button>
    </van-uploader>
  </div>
</template>

<script>
import { deleteFile, uploadFile } from "@/api/image_upload";
export default {
  props:{
    field_key:{
      // 非必填,动态渲染时可同时返回对应的key,方便父组件处理
      type: String,
      default:''
    },
    // 用来判断是否是评论工单时调用此组件
    is_comment:{
      type:Boolean,
      default: false
    },
    // 上传路径
    uploadPath:{
      type:String,
      default:'debug/',
    },
    maxCount:{
      type:Number,
      default:9,
    },
     // 文件url列表
    urlList:{
      type:Array,
      default:()=>[],
    },
  },
  data(){
    return{
      fileList: [],
      baseUrl: 'https://howflow-1253590499.cos.ap-chengdu.myqcloud.com/',
      basePath: 'media/',
    }
  },
  created(){
    this.urlList.forEach(item=>{
      this.fileList.push({url:item})
    })
    if (process.env.NODE_ENV === 'development') {
      this.basePath = "media/debug/"
    }
  },
  methods:{
    // 上传
    uploadImg(files,detail){
      let promiseList = []
      let promiseUpload = (data,file) => {
        return new Promise((resolve, reject) => {
          uploadFile(data, (err, info) =>{
            if (err) {
              file.status = 'failed'
              this.$toast.fail(err)
              reject(err)
            }else{
              file.status = 'done'
              resolve(info)
            }
          })
        })
      }
      if(Object.prototype.toString.call(files)!=='[object Array]'){
        files = [files]
      }
      files.forEach(file =>{
        let f = file.file.name.split('/');
        let filename = new Date().getTime() + f[f.length-1];
        let filePath = this.uploadPath + filename
        let Key = this.basePath + filePath;
        let data = {
          Key: Key,
          file: file.file,
        };
        file.status = 'uploading'
        this.urlList.push(this.baseUrl + Key)
        promiseList.push(promiseUpload(data,file))
      })
      Promise.all(promiseList).then((result) => { 
        // 所有上传完成后
        this.$emit('complete',{
          field_key: this.field_key,
          urlList: this.urlList
        })
      }).catch((error) => {
        console.log(error)
      })
      //图片展示数量超出屏幕时，默认从后往前在屏幕右侧开始展示
      if(this.is_comment){
        let widthNum = this.fileList.length * 83
        if(widthNum > this.$refs.imgScroll.clientWidth){
          this.$nextTick(()=>{
            this.$refs.imgScroll.scrollLeft = widthNum - this.$refs.imgScroll.clientWidth + 88
          })
        }
      }
    },
    deleteImg(file, i){
      if(!file){
        return
      }else if(file.status=='failed'){
        this.fileList.splice(i.index, 1)
        this.urlList.splice(i.index, 1)
        return
      }
      let f =  this.urlList[i.index].split('media/')
      let filePath =  f[f.length-1];
      console.log(filePath)
      deleteFile({filePath: filePath, uploadPath:this.uploadPath}, (err, info) =>{
        console.log(err || info)
        if (err) {
          this.$toast.fail(err)
          return;
        }
        this.fileList.splice(i.index, 1)
        this.urlList.splice(i.index, 1)
      })
    }
  }
}
</script>

<style lang="less" scoped>
*{
  box-sizing: border-box;
}
.upload_image{
  display: flex;
  justify-content: space-between;
  padding: 8px;
}
.comment_upload_image{
  width:9.5333rem;
  overflow-y: scroll;
  height:96px;
  display: flex;
  justify-content: space-between;
  >:nth-child(1){
    position: static !important;
    >:nth-child(1){
      flex-wrap: nowrap;
      margin-top: 0.2133rem;
      position: static !important;
      /deep/.van-uploader__input-wrapper{
        position: absolute;
        bottom:-0.8rem;
        left: 0.9333rem;
        width: 0.8rem;
        height: 0.8rem;
        button{
          background:none !important;
          border:none;
          padding: 0;
          width: 0.8rem;
          height: 0.8rem;
          font-size: 0.4267rem;
          >:nth-child(1){
            color: #38A0F2;
            line-height: 0.8rem;
          }
        }
      }
    }
  }
}
.comment_upload_image::-webkit-scrollbar{
  display: none;
}
</style>
